#!/usr/bin/env python
# Author: Daniel Hewlett

PKG = 'festival'

# All ROS python nodes should have these lines
import roslib; roslib.load_manifest(PKG)
import rospy

from std_msgs.msg import String

# This is needed to execute commands in the shell
import subprocess

pkg_path = roslib.packages.get_pkg_dir('festival')

# Adapted from Stanford repository sail-ros-pkg 
class Speaker():
    def __init__(self):
        # anonymous=true means unique node name and it doesnt get bumped off
        # so we should have this as False
        rospy.init_node('festival', anonymous=False)
        # his declares that your node subscribes to the chatter topic which is of type std_msgs.msgs.String. When new messages are received, callback is invoked with the message as the first argument. 
        rospy.Subscriber("tts", String, self.callback)

    def callback(self, data):
        # write data.data to a tmp file
        tmpFile = pkg_path + "/tts.tmp"
        f = open(tmpFile, "w")
        f.write(data.data)
        f.close()
        print data.data
        
        #errFile = os.path.join(os.curdir, "error.log")
#        errFile = "error.log"
#        errptr = file(errFile, "w")

        cmd = "/usr/bin/festival --tts " + tmpFile

        print cmd

        retval = subprocess.call(cmd, 0, None, None, None, None, shell=True)
        #retval = subprocess.call("festival -h", 0, None, None, None, None, shell=True)

#        errptr.close()

#        if not retval == 0:
#          errptr = file(errFile, "r")
#          errData = errptr.read()
#          errptr.close()
#          raise Exception("Error executing command: " + repr(errData))


if __name__ == '__main__':
    try:
        speaker = Speaker()
        rospy.spin()
    except rospy.ROSInterruptException: pass

